/* 
 * Copyright (c) 2009, Giora Kosoi giorak@gmail.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the project nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Giora Kosoi ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Giora Kosoi BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <sparrow/errors.h>
#include <sparrow/reactor.h>
#include <sparrow/thread_connector.h>

class ThreadQueue
{
    public:
        ThreadQueue(int notify_fd, size_t max_elems);
        ~ThreadQueue();
        bool enqueue(VariantSet *v);
        VariantSet *dequeue();

    private:
        ThreadQueue(const ThreadQueue &other);
        ThreadQueue &operator =(const ThreadQueue &rhs);

        pthread_mutex_t m;

        int fd;
        const size_t MAX_ELEMENTS;
        size_t size;
        std::queue<VariantSet *, std::deque<VariantSet *> > q;
};

ThreadQueue::ThreadQueue(int notify_fd, size_t max_elems)
    :   fd(notify_fd),
        MAX_ELEMENTS(max_elems),
        size(0)
{
    pthread_mutex_init(&m, NULL);
}

ThreadQueue::~ThreadQueue()
{
    pthread_mutex_destroy(&m);
}

bool ThreadQueue::enqueue(VariantSet *v)
{
    bool pushed = false;
    pthread_mutex_lock(&m);
    if(size < MAX_ELEMENTS)
    {
        char buff[1] = {'I'};
        int result = write(fd, buff, sizeof(buff));
        if(result == sizeof(buff))
        {
            q.push(v);
            ++size;
            pushed = true;
        }
        else if(errno == EAGAIN)
        {
            pushed = false;
        }
        else
        {
            throw_error<std::runtime_error>(__FILE__, __LINE__,
                    "failed write: error:  [%s]",
                    strerror(errno));
        }
    }
    pthread_mutex_unlock(&m);
    return pushed;
}

VariantSet *ThreadQueue::dequeue()
{
    VariantSet *v = NULL;
    pthread_mutex_lock(&m);
    if(size > 0)
    {
        v = q.front();
        q.pop();
        --size;
    }
    pthread_mutex_unlock(&m);
    return v;
}


ThreadConnector::ThreadConnector(Reactor *r)
    :   Handler(r),
        q(NULL),
        read_fd(-1),
        write_fd(-1),
        input_token(-1)
{
    int fds[2];
    int result = pipe(fds);
    if(result != 0)
    {
        throw_error<std::runtime_error>(__FILE__, __LINE__, 
                "failed pipe: error: [%s]", 
                strerror(errno));
    }
    read_fd = fds[0];
    write_fd = fds[1];

    result = fcntl(read_fd, F_SETFL, O_NONBLOCK);
    if(result != 0)
    {
        throw_error<std::runtime_error>(__FILE__, __LINE__, 
                "failed fcntl: error: [%s]", 
                strerror(errno));
    }

    result = fcntl(write_fd, F_SETFL, O_NONBLOCK);
    if(result != 0)
    {
        throw_error<std::runtime_error>(__FILE__, __LINE__, 
                "failed fcntl: error: [%s]", 
                strerror(errno));
    }

    // todo make size limit dynamic
    q = new ThreadQueue(write_fd, 65536);

    register_input(0, this, &ThreadConnector::input);
    register_once(this, &ThreadConnector::once);
}

ThreadConnector::~ThreadConnector()
{
    close(read_fd);
    close(write_fd);
    delete q;
}

void ThreadConnector::handle_input(int fd, uint64_t token)
{
    char buff[1];
    int result = read(read_fd, buff, sizeof(buff));
    if(result < 0)
    {
        throw_error<std::runtime_error>(__FILE__, __LINE__,
                "failed read: error [%s]",
                strerror(errno));
    }
    VariantSet *v = q->dequeue();
    push(0, v);
}

void ThreadConnector::handle_error(int fd, uint64_t token)
{
}

void ThreadConnector::handle_timeout(uint64_t token)
{
}

void ThreadConnector::once(VariantSet *v)
{
    input_token = get_reactor()->create_token();
    get_reactor()->register_input_handler(read_fd, this, input_token);
}

void ThreadConnector::input(VariantSet *v)
{
    if(!q->enqueue(v))
    {
        push(1, v);
    }
}

